package com.ssy.lingxi.order.handler.validator;

import com.ssy.lingxi.order.handler.annotation.BigDecimalStringAnnotation;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * 商品定价类型校验注解验证类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-07-17
 */
public class BigDecimalStringValidator implements ConstraintValidator<BigDecimalStringAnnotation, String> {
    private boolean nullable = true;

    @Override
    public void initialize(BigDecimalStringAnnotation constraintAnnotation) {
        nullable = constraintAnnotation.nullable();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!StringUtils.hasText(value)) {
            return nullable;
        }

        try {
            BigDecimal bigDecimal = new BigDecimal(value);
            return bigDecimal.compareTo(BigDecimal.ZERO) >= 0;
        } catch (Exception e) {
            return false;
        }
    }
}
